package com.xwj.exception.solution_1.handler;

import com.xwj.common.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @Author: xiaowajiang
 * @Date: 2022-04-05 19:59
 * @Description: 基于 SpringBoot 的全局统一异常处理
 **/
@Slf4j
@RestController
@EnableConfigurationProperties({ServerProperties.class})
public class ExceptionController implements ErrorController {

    private static final String ERROR_PATH = "/error";
    private ErrorAttributes errorAttributes;

    @Autowired
    private ServerProperties serverProperties;

    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }

    @Autowired
    public ExceptionController(ErrorAttributes errorAttributes) {
        this.errorAttributes = errorAttributes;
    }

    /**
     * web页面错误处理
     */
    @RequestMapping(value = ERROR_PATH, produces = "text/html")
    @ResponseBody
    public ModelAndView errorHtml404(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView modelAndView = null;
        ServletWebRequest requestAttributes = new ServletWebRequest(request);
        Map<String, Object> model = getErrorAttributes(requestAttributes, isIncludeStackTrace(request, MediaType.ALL));
        model.put("queryString", request.getQueryString());
        // 根据不同状态码返回不同页面，这里以404/500为例
        HttpStatus status = getStatus(request);
        if (status.value() == HttpStatus.INTERNAL_SERVER_ERROR.value()) { // 500
            modelAndView = new ModelAndView("500", model);
        } else if (status.value() == HttpStatus.NOT_FOUND.value()) { // 404
            modelAndView = new ModelAndView("404", model);
        } else {
            modelAndView = new ModelAndView("error", model);
        }
        return modelAndView;
    }

    /**
     * 除web页面外的错误处理，比如json/xml等
     */
    @RequestMapping(value = ERROR_PATH)
    @ResponseBody
    public R errorApiHandler(HttpServletRequest request) {
        ServletWebRequest requestAttributes = new ServletWebRequest(request);
        Map<String, Object> attr = getErrorAttributes(requestAttributes, isIncludeStackTrace(request, MediaType.ALL));
        HttpStatus status = getStatus(request);
        return R.error(status.value() + "", attr.get("message").toString());
    }

    /**
     * 确定是否应该包含 StackTrace 属性
     *
     * @param request
     * @param produces
     * @return
     */
    protected boolean isIncludeStackTrace(HttpServletRequest request, MediaType produces) {
        ErrorProperties.IncludeStacktrace include = this.serverProperties.getError().getIncludeStacktrace();
        if (include == ErrorProperties.IncludeStacktrace.ALWAYS) {
            return true;
        }
        return include == ErrorProperties.IncludeStacktrace.ON_TRACE_PARAM && getTraceParameter(request);
    }

    /**
     * 获取错误的信息
     *
     * @param webRequest
     * @param includeStackTrace
     * @return
     */
    private Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
        return this.errorAttributes.getErrorAttributes(webRequest, includeStackTrace);
    }

    /**
     * 是否包含 trace
     *
     * @param request
     * @return
     */
    private boolean getTraceParameter(HttpServletRequest request) {
        String parameter = request.getParameter("trace");
        return parameter != null && !"false".equalsIgnoreCase(parameter);
    }

    /**
     * 获取错误编码
     *
     * @param request
     * @return
     */
    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request
                .getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        try {
            return HttpStatus.valueOf(statusCode);
        } catch (Exception ex) {
            log.error("获取当前 HttpStatus 发生异常", ex);
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
    }
}